package com.fast.alden.common.web;


import com.fast.alden.common.annotation.IgnoreRestControllerResponseAdvice;
import com.fast.alden.common.entity.dto.ResponseResult;
import com.fast.alden.common.util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应实体封装切面，对于有RestController注解的类，方法没有IgnoreRestControllerResponseAdvice注解，
 * 且response不是ResponseResult类型时启用beforeBodyWrite
 */
// todo: warning: 由于是在common层定义，无法获取具体的控制器所属包，还需完善
@RestControllerAdvice(basePackages = {"com.fast.alden"})
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 方法没有IgnoreRestControllerResponseAdvice注解，且response不是ResponseResult类型时启用beforeBodyWrite
        return !returnType.hasMethodAnnotation(IgnoreRestControllerResponseAdvice.class)
                && !returnType.getParameterType().isAssignableFrom(ResponseResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回值是void类型，直接返回200状态信息
        if (returnType.getParameterType().isAssignableFrom(void.class)) {
            return ResponseResult.success();
        }
        if (!(body instanceof ResponseResult)) {
            // todo: warning: RestController方法上返回值类型为String时，响应的Content-Type是text/plain，需要手动指定为application/json
            if (body instanceof String) {
                try {
                    return JsonUtils.toJSON(ResponseResult.success(body));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
            return ResponseResult.success(body);
        }
        return body;
    }
}
